<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.id"> 
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="!!cartInfo.isChecked" @change="checkCartInfoState(cartInfo)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{cartInfo.skuName}}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{cartInfo.skuPrice}}.00</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)"  @click="changeSkuNum('decrement',cartInfo)" class="mins">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" minnum="1" 
            @change="changeSkuNum('change',cartInfo, $event)"
            class="itxt">
            <a href="javascript:void(0)" class="plus" @click="changeSkuNum('increment',cartInfo)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{cartInfo.skuPrice * cartInfo.skuNum}}</span>
          </li>
          <li class="cart-list-con7">
            <a href="#none" class="sindelet"  @click="delOneCartInfo(cartInfo)" >删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>

      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="showDialogByDelSelected()">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{selectedShopNum}}</span>件商品</div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{selectedMoney}}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>
    <Dialog :isShow.sync="isShow">
      <template v-slot:header>
        提示
      </template>
      <template>
        <p>您真的要删除{{isDelOne?'此条商品':'所选择的商品'}}数据吗?</p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn" @click="isShow=false">取消</button>
          <button class="btn primary" @click="delCartInfo">确认</button>
        </div>
      </template>

    </Dialog>
  </div>
</template>

<script>
import {reqShopCartListData, reqChangeShopCartInfoState, reqUpdateShopCartInfoState, reqDelOneShopCrtInfo,reqDelCheckedShopInfo, reqAddOrUpdataCart} from '@/api'
import {skuNumReg} from '@/utils/reg'
  export default {
    name: 'ShopCart',

    data(){
      return {
          cartInfoList: [],
          isShow: false,
          skuId: '',
          isDelOne: false,
          skuIdList: [], //选中用于删除的商品
          leftCartInfoList:[] //剩余未选中商品
      }
    },

  methods: {
    //更新单个订单
    async checkCartInfoState(cartInfo) {
      let isChecked = 1- cartInfo.isChecked
      const result = await reqChangeShopCartInfoState(cartInfo.skuId,
        isChecked)
        if(result.code === 200) {
          cartInfo.isChecked = isChecked
        } else {
          alert ('修改失败...')
        }
    },
    //删除按钮收集商品ID
    delOneCartInfo(cart) {
      this.skuId = cart.skuId
      this.isShow = true
      this.isDelOne = true
    },
    //单击批量删除按钮时弹出对话框 
    showDialogByDelSelected() {
      this.skuIdList = []
      this.leftCartInfoList = []
      this.cartInfoList.forEach(item => {
        if(item.isChecked) {
          this.skuIdList.push(item.skuId)
        } else {
          this.leftCartInfoList.push(item)
        }
      })
      //弹出确认框
      this.isShow = true
      //区分单选和多选
      this.isDelOne = false
    },
    //点击删除确认按钮时
    async delCartInfo() {
      let result
      if(this.isDelOne) {
        result = await reqDelOneShopCrtInfo(this.skuId)
        if(result.code === 200) {
        this.cartInfoList = this.cartInfoList.filter(item => {
          return item.skuId !==this.skuId
        })
          this.isShow = false //隐藏对话框
          return
        } else {
          console.log('删除失败');
        }
      } 
      //多个选中删除
      result = await reqDelCheckedShopInfo({data:this.skuIdList})
      if(result.code === 200) {
        this.cartInfoList = this.leftCartInfoList
        this.isShow =false
      }

    } ,
    //更改商品数量
    async changeSkuNum(type,cartInfo, $event) {
      let num = 0
      let { skuId} = cartInfo
      switch(type) {
        case 'increment': 
        if(cartInfo.skuNum < 200) {
          cartInfo.skuNum++
          num++
        }
        break

        case 'decrement':
          if(cartInfo.skuNum > 1) {
            cartInfo.skuNum--
           num--
          }
          break

          case'change':
          let newNum = $event.target.value
          if(skuNumReg.test(newNum)) {
            num = newNum - cartInfo.skuNum
            cartInfo.skuNum = newNum
            if(newNum > 200) {
              num = 200 - cartInfo.skuNum
              cartInfo.skuNum = 200
            }
          } else {
            $event.target.value = cartInfo.skuNum
          }
          break
      }
      if(num === 0) return
      await reqAddOrUpdataCart(skuId, num)
    },
    //获取购物商品数据
    async getShopCartListData() {
      const result = await reqShopCartListData()
      if(result.code === 200) {
        this.cartInfoList = result.data[0] ? result.data[0].cartInfoList : []
        // this.cartInfoList = result.data[0].cartInfoList  
      }else {
        console.log(result.message)
      }
    }
  
  },

  watch:{
    isShow: {
      immediate: true,
      handler() {
        if(this.isShow) {
          document.documentElement.style.overflow ="hidden"
        } else {
            document.documentElement.style.overflow ="auto"
        }
      }
    }

  },
  computed: {
    //全选或不选
    checkAll: {
      get() {
        return this.cartInfoList.length && this.cartInfoList.every(item => item.isChecked === 1)
      },
      async set(val) {
        let isChecked = val ? 1 : 0

        //创建数组收集每个订单id
        let skuIdList = []
        this.cartInfoList.forEach(item => {
          item.isChecked = isChecked
          skuIdList.push(item.skuId)
          })
        const result = await reqUpdateShopCartInfoState(skuIdList,isChecked )
        if(result.code == 200) {
          console.log('ok')
        } else {
          console.log('更新失败');
        }
      }
    },
    //选择商品的数量
    selectedShopNum() {
      return this.cartInfoList.reduce((pre,cur) => {
        return pre + cur.isChecked
      },0)
    },
    //选择商品的金额
    selectedMoney() {
      return this.cartInfoList.reduce((prev,curr) => {
        return prev +curr.skuPrice*curr.skuNum*curr.isChecked
      },0)
    }
  },


    mounted() {
      //获取数据渲染页面
      this.getShopCartListData()
    },

  }

</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }
			

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .dialog {
  // 最外层
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
}

// 内层水平垂直居中
.dialog-wrap {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 460px;
  height: 130px;
  box-sizing: border-box; // 内减模式
  padding: 12px;
  transform: translate(-50%, -50%);
  background-color: #fff;
     .dialog-header {
      display: flex;
      justify-content: space-between;
      font-size: 18px;
      .dialog-header-close {
        border: none; // 去掉边框
        outline: none; // 去掉环绕线
        background-color: transparent; // 透明色
        cursor: pointer;
      }
    }
    // 中间
    .dialog-body {
      text-align: center;
      font-size: 16px;
      padding: 10px;
    }
    .btn-footer {
        position: absolute;
        right: 40px;
        bottom: 20px;
        .btn {
            width: 62px;
            height: 32px;
            font-size: 14px;
            margin-left: 16px;
            border-width:1px;
            border-radius: 10%;
            cursor:pointer;
            &.primary {
            background-color: rgb(102, 177, 255);
            color:#fff;
            }
        }
    }
}
}
</style>